import json
import requests
import hashlib
import time

# 应用信息
app_id = "AK20220421NKYFKE"
app_key = "59ccd8febdea50e5902232145c623cc1"
openapi_host = "http://182.160.1.149/open"

def _sig(content_md5, url, date):
    sha1 = hashlib.sha1()
    sha1.update(app_key.lower().encode('utf-8'))
    sha1.update(content_md5.encode('utf-8'))
    sha1.update(url.encode('utf-8'))
    sha1.update("application/json".encode('utf-8'))
    sha1.update(date.encode('utf-8'))

    return "WPS-3:%s:%s" % (app_id, sha1.hexdigest())


def request(method, host, uri, body=None, cookie=None, headers=None):
    requests.packages.urllib3.disable_warnings()

    if method == "PUT" or method == "POST" or method == "DELETE":
        body = json.dumps(body)

    if method == "PUT" or method == "POST" or method == "DELETE":
        content_md5 = hashlib.md5(body.encode('utf-8')).hexdigest()
    else:
        content_md5 = hashlib.md5("".encode('utf-8')).hexdigest()

    date = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())
    print(date)
    exit(0)

    header = {"Content-type": "application/json"}
    header['X-Auth'] = _sig(content_md5, uri, date)
    header['Date'] = date
    header['Content-Md5'] = content_md5
    if headers != None:
        header = {}
        for key, value in headers.items():
            header[key] = value

    url = "%s%s" % (host, uri)
    r = requests.request(method, url, data=body,
                         headers=header, cookies=cookie, verify=False)

    print("[response]: status=[%d],URL=[%s],data=[%s]" % (r.status_code, url, r.text))

    return r.status_code, r.text


def get_company_token():
    url = "/auth/v1/app/inscope/token?app_id=%s&scope=%s" % (app_id, "file_preview")

    status, rsp = request("GET", openapi_host, url, None, None, None)
    rsp = json.loads(rsp)
    print(rsp)

    if rsp.__contains__('company_token'):
        return rsp["company_token"]
    else:
        print("no company-token found in response, authorized failed")
        exit(-1)


if __name__ == '__main__':
    # 获取token
    company_token = get_company_token()